package com.xie.smfs.client;

import com.xie.smfs.registry.ModEffects;
import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents;
import net.minecraft.client.MinecraftClient;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.effect.StatusEffectInstance;

public class EffectRenderHandler {
    // 保存原始状态
    private static float[] originalColor = new float[]{1.0F, 1.0F, 1.0F, 1.0F};
    private static float originalFogStart = 0.0F;
    private static float originalFogEnd = 1.0F;
    private static float[] originalFogColor = new float[]{0.0F, 0.0F, 0.0F, 0.0F};

    // 状态标记
    private static boolean isRedEffectActive = false;
    private static boolean isFogEffectActive = false;
    private static boolean isRestoring = false;

    public static void register() {
        // 在渲染开始前检查效果状态
        WorldRenderEvents.START.register(context -> {
            PlayerEntity player = MinecraftClient.getInstance().player;
            if (player == null) return;

            boolean hadRedEffect = isRedEffectActive;
            boolean hadFogEffect = isFogEffectActive;

            // 检查当前效果状态
            isRedEffectActive = player.hasStatusEffect(ModEffects.RED_GHOST_DOMAIN) ||
                    player.hasStatusEffect(ModEffects.RED_GHOST_DOMAIN_TARGET);
            isFogEffectActive = player.hasStatusEffect(ModEffects.THICK_FOG);

            // 如果效果刚刚消失，立即恢复原始设置
            if ((hadRedEffect && !isRedEffectActive) || (hadFogEffect && !isFogEffectActive)) {
                restoreOriginalSettings();
            }

            // 保存原始设置（只在第一次检测到效果时）
            if ((isRedEffectActive || isFogEffectActive) && !isRestoring) {
                saveOriginalSettings();
            }
        });

        // 在设置阶段应用效果
        WorldRenderEvents.AFTER_SETUP.register(context -> {
            if (isRestoring) return;

            PlayerEntity player = MinecraftClient.getInstance().player;
            if (player == null) return;

            // 获取红色鬼域效果等级并应用
            if (isRedEffectActive) {
                StatusEffectInstance effectInstance = player.getStatusEffect(ModEffects.RED_GHOST_DOMAIN);
                if (effectInstance == null) {
                    effectInstance = player.getStatusEffect(ModEffects.RED_GHOST_DOMAIN_TARGET);
                }
                if (effectInstance != null) {
                    int amplifier = effectInstance.getAmplifier();
                    applyRedEffect(amplifier);
                }
            }
            // 应用浓雾效果
            else if (isFogEffectActive) {
                applyFogEffect();
            }
        });

        // 在渲染结束后确保恢复设置
        WorldRenderEvents.LAST.register(context -> {
            PlayerEntity player = MinecraftClient.getInstance().player;
            if (player == null) return;

            // 检查效果是否仍然存在，如果不存在则恢复
            boolean currentRedEffect = player.hasStatusEffect(ModEffects.RED_GHOST_DOMAIN) ||
                    player.hasStatusEffect(ModEffects.RED_GHOST_DOMAIN_TARGET);
            boolean currentFogEffect = player.hasStatusEffect(ModEffects.THICK_FOG);

            if ((!currentRedEffect && isRedEffectActive) || (!currentFogEffect && isFogEffectActive)) {
                restoreOriginalSettings();
                isRedEffectActive = currentRedEffect;
                isFogEffectActive = currentFogEffect;
            }
        });
    }

    private static void saveOriginalSettings() {
        originalColor = RenderSystem.getShaderColor().clone();
        originalFogStart = RenderSystem.getShaderFogStart();
        originalFogEnd = RenderSystem.getShaderFogEnd();
        originalFogColor = RenderSystem.getShaderFogColor().clone();
    }

    private static void restoreOriginalSettings() {
        isRestoring = true;
        try {
            RenderSystem.setShaderColor(originalColor[0], originalColor[1], originalColor[2], originalColor[3]);
            RenderSystem.setShaderFogStart(originalFogStart);
            RenderSystem.setShaderFogEnd(originalFogEnd);
            RenderSystem.setShaderFogColor(originalFogColor[0], originalFogColor[1], originalFogColor[2], originalFogColor[3]);

            // 重置状态标记
            isRedEffectActive = false;
            isFogEffectActive = false;
        } finally {
            isRestoring = false;
        }
    }

    private static void applyRedEffect(int amplifier) {
        // 基础红色值0.8F，每级增加0.1F，但不超过1.0F
        float redValue = Math.min(0.8F + (amplifier * 0.1F), 1.0F);
        RenderSystem.setShaderColor(redValue, 0.0F, 0.0F, originalColor[3]);
        RenderSystem.setShaderFogStart(0.5F);
        RenderSystem.setShaderFogEnd(32.0F);
        RenderSystem.setShaderFogColor(redValue, 0.0F, 0.0F, 1.0F);
    }

    private static void applyFogEffect() {
        RenderSystem.setShaderFogStart(0.5F);
        RenderSystem.setShaderFogEnd(8.0F);
        RenderSystem.setShaderColor(0.8F, 0.8F, 0.8F, 0.7F);
    }

    // 提供一个公共方法来强制恢复设置（可以在效果移除时调用）
    public static void forceRestore() {
        restoreOriginalSettings();
    }
}